package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.service.WorkspaceService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sky.constant.MessageConstant.ADDRESS_BOOK_IS_NULL;
import static com.sky.constant.MessageConstant.SHOPPING_CART_IS_NULL;
import static com.sky.entity.Orders.PENDING_PAYMENT;
import static com.sky.entity.Orders.UN_PAID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    /**
     * 提交订单
     * @param submitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO submitDTO) {
        //1.根据地址簿id获取地址簿对象
        AddressBook addressBook = addressBookMapper.getById(submitDTO.getAddressBookId());
        //2.如果地址簿对象为null抛出异常
        if (addressBook==null){
            throw new AddressBookBusinessException(ADDRESS_BOOK_IS_NULL);
        }
//        //2.1判断当前地址和店铺是否超过配送距离
//        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //3.根据userId购物车数据列表
        List<ShoppingCart> list = shoppingCartService.list();
        //4.如果购物车数据列表为空或者是长度为0抛出异常
        if (CollectionUtils.isEmpty(list)){
            throw new ShoppingCartBusinessException(SHOPPING_CART_IS_NULL);
        }
        //5.创建订单对象
        Orders orders = new Orders();
        //6.订单对象赋值
        BeanUtils.copyProperties(submitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //7.插入订单表订单数据(主键回写)
        orderMapper.insert(orders);
        //8.创建订单详情对象集合
        List<OrderDetail> orderDetailList = list.stream().map(shoppingCart -> {
            //9.赋值订单详情对象集合
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail,"id");
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        //10.批量插入订单详情表
        orderDetailMapper.insertBatch(orderDetailList);
        //11.清空用户购物车
        shoppingCartService.clean();
        //12.封装OrderSubmitVO
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
    }
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject =new JSONObject();


        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
        return orderPaymentVO;
    }

//太难了不会省略掉
//    @Value("${sky.shop.address}")
//    private String shopAddress;
//
//    @Value("${sky.baidu.ak}")
//    private String ak;
//
//    /**
//     * 检查客户的收货地址是否超出配送范围
//     * @param address
//     */
//    private void checkOutOfRange(String address) {
//        Map map = new HashMap();
//        map.put("address",shopAddress);
//        map.put("output","json");
//        map.put("ak",ak);
//
//        //获取店铺的经纬度坐标
//        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
//
//        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
//        if(!jsonObject.getString("status").equals("0")){
//            throw new OrderBusinessException("店铺地址解析失败");
//        }
//
//        //数据解析
//        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
//        String lat = location.getString("lat");
//        String lng = location.getString("lng");
//        //店铺经纬度坐标
//        String shopLngLat = lat + "," + lng;
//
//        map.put("address",address);
//        //获取用户收货地址的经纬度坐标
//        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
//
//        jsonObject = JSON.parseObject(userCoordinate);
//        if(!jsonObject.getString("status").equals("0")){
//            throw new OrderBusinessException("收货地址解析失败");
//        }
//
//        //数据解析
//        location = jsonObject.getJSONObject("result").getJSONObject("location");
//        lat = location.getString("lat");
//        lng = location.getString("lng");
//        //用户收货地址经纬度坐标
//        String userLngLat = lat + "," + lng;
//
//        map.put("origin",shopLngLat);
//        map.put("destination",userLngLat);
//        map.put("steps_info","0");
//
//        //路线规划
//        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
//
//        jsonObject = JSON.parseObject(json);
//        if(!jsonObject.getString("status").equals("0")){
//            throw new OrderBusinessException("配送路线规划失败");
//        }
//
//        //数据解析
//        JSONObject result = jsonObject.getJSONObject("result");
//        JSONArray jsonArray = (JSONArray) result.get("routes");
//        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
//
//        if(distance > 5000){
//            //配送距离超过5000米
//            throw new OrderBusinessException("超出配送范围");
//        }
//    }


    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //来单提醒
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 1);
        jsonObject.put("orderId",ordersDB.getId());
        jsonObject.put("content","订单号: "+ordersDB.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(jsonObject));

    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        Page<OrderVO> ordersList =orderMapper.pageQueryOrderVOList(ordersPageQueryDTO);
        // 分页条件查询
//        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
//
//        List<OrderVO> list = new ArrayList();
//
//        // 查询出订单明细，并封装入OrderVO进行响应
//        if (page != null && page.getTotal() > 0) {
//            for (Orders orders : page) {
//                Long orderId = orders.getId();// 订单id
//
//                // 查询订单明细
//                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
//
//                OrderVO orderVO = new OrderVO();
//                BeanUtils.copyProperties(orders, orderVO);
//                orderVO.setOrderDetailList(orderDetails);
//
//                list.add(orderVO);
//            }
//        }
        return new PageResult(ordersList.getTotal(), ordersList);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO details(Long id) {
//        // 根据id查询订单
//        Orders orders = orderMapper.getById(id);
//
//        // 查询该订单对应的菜品/套餐明细
//        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
//
//        // 将该订单及其详情封装到OrderVO并返回
//        OrderVO orderVO = new OrderVO();
//        BeanUtils.copyProperties(orders, orderVO);
//        orderVO.setOrderDetailList(orderDetailList);

        return orderMapper.getQueryOrderVO(id);
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //获取orderVo
        Page<OrderVO> orderVOPage = orderMapper.pageQueryOrderVOList(ordersPageQueryDTO);
        //处理orderDishes字段
        List<OrderVO> result = orderVOPage.stream().map(orderVO -> {
            List<OrderDetail> orderDetailList = orderVO.getOrderDetailList();
            List<String> dishName = orderDetailList.stream().map(orderDetail -> {
                return orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            }).collect(Collectors.toList());
            String dishesName = String.join(" ", dishName);
            //设置处理orderDishes字段
            orderVO.setOrderDishes(dishesName);
            return orderVO;
        }).collect(Collectors.toList());

//        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
//
//        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
//        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(orderVOPage.getTotal(), result);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
//        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
//        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
//        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
//
//        // 将查询出的数据封装到orderStatisticsVO中响应
//        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
//        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
//        orderStatisticsVO.setConfirmed(confirmed);
//        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderMapper.countOrderStatisticsVO();
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());
        Orders orders = new Orders();
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            orders.setPayStatus(Orders.REFUND);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间

        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 催单
     *
     * @param id
     * @return
     */
    public void reminder(Long id) {
        // 1.根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 2.校验订单是否存在，并且状态为2
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //3.催单通知
        //来单提醒
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 2);
        jsonObject.put("orderId",ordersDB.getId());
        jsonObject.put("content","订单号: "+ordersDB.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(jsonObject));
    }



    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
//        //1.获取所有要统计的天数列表  10-1 10-2 10-3
//        List<LocalDate> dateList = begin.datesUntil(end.plusDays(1), Period.ofDays(1)).collect(Collectors.toList());
//        //2.循环天数列表查询每天的营业额添加到营业额列表
//        List<Double> doubleList = new ArrayList<>();
//        for (LocalDate localDate : dateList) {
//            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
//            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
//            Map map = new HashMap<>();
//            map.put("begin",beginTime);
//            map.put("end",endTime);
//            map.put("status",Orders.COMPLETED);
//            Double countTurnover = orderMapper.countTurnover(map);
//            if (countTurnover == null){
//                countTurnover =0.0;
//            }
//            doubleList.add(countTurnover);
//        }
//        //3.返回数据TurnoverReportVO
//        return   TurnoverReportVO.builder()
//                .dateList(StringUtils.join(dateList,","))
//                .turnoverList(StringUtils.join(doubleList,","))
//                .build();
            //1.获取天数集合
            List<LocalDate> dateList = begin.datesUntil(end.plusDays(1), Period.ofDays(1)).collect(Collectors.toList());
            //2.查询每天营业
            Map map = new HashMap<>();
            map.put("begin",begin);
            map.put("end",end);
            map.put("status",Orders.COMPLETED);
            List<Turnover> turnoverList = orderMapper.countTurnoverList(map);
            //2.1获取map key是日期value是营业额
            Map<LocalDate, Double> turnMap = turnoverList.stream().collect(Collectors.toMap(Turnover::getDate, Turnover::getTurnover));
            //获取营业额集合
            List<Double> turnOver = dateList.stream().map(date -> turnMap.getOrDefault(date,0.0)).collect(Collectors.toList());
            return   TurnoverReportVO.builder()
            .dateList(StringUtils.join(dateList,","))
            .turnoverList(StringUtils.join(turnOver,","))
            .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.获取日期集合
        List<LocalDate> dateList = begin.datesUntil(end.plusDays(1), Period.ofDays(1)).collect(Collectors.toList());
        //2.遍历日期集合,查询当天的有效订单和总订单
        List<Integer> totalList = new ArrayList();
        List<Integer> vaildList = new ArrayList();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            //2.1获取当天总订单
             Integer total=orderMapper.countOrders(map);
            totalList.add(total);
            //2.2获取当天有效订单
            map.put("status",Orders.COMPLETED);
            Integer vaild=orderMapper.countOrders(map);
            vaildList.add(vaild);
        });
        //3.获取时间段内订单总数
//        Integer totalCount=0;
//        Integer vaildCount=0;
//        for (Integer integer : totalList) {
//            totalCount += integer;
//        }
        Integer totalCount = totalList.stream().reduce(Integer::sum).get();
        //4.获取时间段内有效订单总数
//        for (Integer integer : vaildList) {
//            vaildCount += integer;
//        }
        Integer vaildCount = vaildList.stream().reduce(Integer::sum).get();
        Double ordersCompleteRate =0.0;
        //5.计算时间段内的订单完成率
        if(totalCount!=0){
            ordersCompleteRate = Double.valueOf(vaildCount)/totalCount;
        }
        return OrderReportVO.builder()
                .validOrderCount(vaildCount)
                .totalOrderCount(totalCount)
                .orderCompletionRate(ordersCompleteRate)
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(totalList,","))
                .validOrderCountList(StringUtils.join(vaildList,","))
                .build();
    }

    /**
     * top10菜品套餐统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1.查询top10菜品套餐
        List<GoodsSalesDTO> goodsSalesDTOS =orderMapper.top10(begin,end);
        //2.获取菜品名称 销量集合
        List<String>  nameList =goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numList =goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numList,","))
                .build();
    }
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 导出运营数据表
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        ServletOutputStream outputStream = null;
        XSSFWorkbook excel =null;
        try {
            //1.获取运营数据报表模版excel对象
            //1.1获取类加载器
            ClassLoader classLoader = this.getClass().getClassLoader();
            //1.2加载模版excel
            InputStream in = classLoader.getResourceAsStream("运营数据报表模板.xlsx");
            excel = new XSSFWorkbook(in);
            //2.获取运营概览数据
            LocalDate now = LocalDate.now();
            LocalDate begin = now.minusDays(30);
            BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(now, LocalTime.MIN));
            //3.写入到excel对象
            //3.1写入时间
            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间: "+begin+"至"+now.minusDays(1));
            //3.1写入概览数据
            XSSFRow row3 = sheet.getRow(3);
            row3.getCell(2).setCellValue(businessData.getTurnover());
            row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row3.getCell(6).setCellValue(businessData.getNewUsers());
            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(2).setCellValue(businessData.getValidOrderCount());
            row4.getCell(4).setCellValue(businessData.getUnitPrice());
            //3.2写入明细数据
            for (int i = 0; i < 30; i++) {
                businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(begin, LocalTime.MAX));
                XSSFRow rowDetail = sheet.getRow(7 + i);
                rowDetail.getCell(1).setCellValue(String.valueOf(begin));
                rowDetail.getCell(2).setCellValue(businessData.getTurnover());
                rowDetail.getCell(3).setCellValue(businessData.getValidOrderCount());
                rowDetail.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                rowDetail.getCell(5).setCellValue(businessData.getUnitPrice());
                rowDetail.getCell(6).setCellValue(businessData.getNewUsers());
                begin = begin.plusDays(1);
            }
            //4.通过流写到浏览器下载文件地址
            outputStream = response.getOutputStream();
            excel.write(outputStream);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //5关闭资源
            try {
                outputStream.close();
                excel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
